package com.g4.shoppingback.service.impl;

import com.g4.shoppingback.common.ImagesVo;
import com.g4.shoppingback.service.ImagesVoService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class ImagesVoServiceImpl implements ImagesVoService {

    //windows磁盘地址
    private String preFilePath="D:\\classgitee\\mishop-back\\src\\main\\resources\\static\\upload";

    //TODO:网路路径上传的地址需要和前端确定
    private String preURLPath="http://imagesVo.mishop.com";
    @Override
    public ImagesVo upload(MultipartFile file) {
        //第一步: 校验图片类型
        //1.获取文件名称  abc.JPG
        //2.bug: 文件名称大小写问题 全部转化为小写
        String fileName = file.getOriginalFilename().toLowerCase();
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
            //如果图片不满足条件,则程序终止
            return null;
        }
        //第二步: 校验是否为恶意程序
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            if(height==0 || width==0){
                return null;
            }

            //第三步: 分目录存储 提高检索的效率  按照时间将目录划分 /yyyy/MM/dd/
            String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());

            // 磁盘地址+日期地址
            String fileDir = preFilePath + datePath;

            //创建目录
            File dirFile = new File(fileDir);
            if(!dirFile.exists()){//目录没有的时候,应该创建目录
                dirFile.mkdirs();
            }

            //第四步: 防止文件重名
            String uuid = UUID.randomUUID().toString().replace("-","");
            int index = fileName.lastIndexOf(".");

            //获取数据 .jpg
            String fileType = fileName.substring(index);

            //新文件名称
            fileName = uuid + fileType;
            //第五步: 实现文件上传
            // D:/JT-SOFT/image/2022/01/10/uuid.jpg
            String filePath = fileDir + fileName;
            file.transferTo(new File(filePath));

            //第六步: 封装ImageVO返回数据    /2022/01/10/uuid.jpg
            String virtualPath = datePath + fileName;

            //第七步: 封装网络地址 http://image.jt.com/2022/01/10/uuid.jpg
            String urlPath =  preURLPath + virtualPath;
            System.out.println(urlPath);
            return new ImagesVo(virtualPath,urlPath,fileName);

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void deleteImages(String Path) {
        String path = preFilePath + Path;
        File file =new File(path);
        if (file.exists()){
            file.delete();
        }
    }
}
